package com.roomio.core.security.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.roomio.core.security.model.User;
import com.roomio.core.security.service.UserInfoService;
import com.roomio.dao.UserInfoDAO;

@Service
@Transactional
public class UserInfoServiceImpl implements UserInfoService {
	@Autowired
	private UserInfoDAO userInfoDAO;
	/* (non-Javadoc)
	 * @see com.roomio.service.impl.UserInfoService#persist()
	 */
	@Override
	public void persist(User user) {
		userInfoDAO.save(user);
	}

	@Override
	public User findById(Long id) {
		return userInfoDAO.findById(id);
	}

	@Override
	public int countUserInfoes() {
		return userInfoDAO.count();
	}

	@Override
	public List<User> findAllUserInfoes() {
		return userInfoDAO.findAll();
	}

	@Override
	public void merge(User user) {
		user.setModifiedDate(new Date());
		userInfoDAO.update(user);
	}

	@Override
	public void deleteByEmail(String username) {
		User user = userInfoDAO.findUserByEmail(username);
		user.setEnabled(false);
		merge(user);
	}
	
	@Override
	public void delete(Long id) {
		userInfoDAO.deleteById(id);
	}

	@Override
	public UserDetails findByIdentityUrl(String username) {
		List<User> userList = userInfoDAO.findByQuery("from User u where identityUrl=:username ", new String[]{"username"}, new Object[]{username});
			if(userList!= null && userList.size()>0){
				return userList.get(0);
			}else{
				return null;
		}
	}
	
	@Override
	public User findByEmail(String email) {
		return userInfoDAO.findUserByEmail(email);
	}

	@Override
	public List<User> findUserInfoEntries(int firstResult, int sizeNo) {
		return userInfoDAO.findAll(firstResult, sizeNo);
	}
	
}
